﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SXICE.Core.Domains;
using SXICE.Core.Models;
using SXICE.IService;
using SXICE.WebAPI.Models;
using SXICE.Core.Helpers;
using SXICE.WebAPI.Utilities;
using System.Collections.Generic;
using AutoMapper;
using SXICE.WebAPI.Models.DTOs;
using SXICE.IService.Models;
using SXICE.IRepository.Models;

namespace SXICE.WebAPI.Controllers
{
    /// <summary>
    /// 客户控制器
    /// </summary>
    [Route("")]
    [Authorize]
    public class CustomerController : ControllerBase
    {
        private readonly ICustomerService customerService;
        private readonly JwtSettings jwtSettings;

        public CustomerController(ICustomerService customerService, JwtSettings jwtSettings)
        {
            this.customerService = customerService;
            this.jwtSettings = jwtSettings;
        }

        /// <summary>
        /// 根据身份证号登录
        /// </summary>
        /// <param name="customer">要登录的用户信息</param>
        /// <returns>结果</returns>
        [AllowAnonymous]
        [HttpPost]
        public ReturnResult<string> LoginByIDNumber([FromBody] Customer customer)
        {
            var result = customerService.LoginByIDNumber(customer);
            if (!result.Success)
                return result.ToErrorResult<string>();
            var token = JwtHelper.GenerateToken(new CustomerClaimsPrincipal
            {
                Id = result.Result.Id,
                IDNumber = result.Result.IDNumber,
                Phone = result.Result.Phone,
                Name = result.Result.Name
            }, jwtSettings);
            if (jwtSettings.AuthorizationType == AuthorizationTypeEnum.Cookie)
                HttpContext.Response.Cookies.Append("Authorization", token, new Microsoft.AspNetCore.Http.CookieOptions
                {
                    HttpOnly = true
                });
            return token.ToResult();
        }

        /// <summary>
        /// 登出
        /// </summary>
        [AllowAnonymous]
        [HttpGet]
        public void LogOut(string type)
        {
            customerService.LogOut(WorkContext.ToCustomer, type);
        }
    }
}
